package com.linksfield.topup.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.linksfield.topup.config.dto.CalculateResultParamVo;
import com.linksfield.topup.config.dto.PageAndSort;
import com.linksfield.topup.config.dto.StringOutputConstant;
import com.linksfield.topup.entity.common.PartnerConfigContent;
import com.linksfield.topup.entity.common.PartnerConfigLang;
import com.linksfield.topup.entity.common.PartnerConfigPay;
import com.linksfield.topup.entity.common.SysOperate;
import com.linksfield.topup.entity.servserapi.JsonConstant;
import com.linksfield.topup.entity.servserapi.querydeviceorder.request.RequestQueryDeviceOrder;
import com.linksfield.topup.entity.servserapi.querydeviceorder.response.ResponseQueryDeviceOrder;
import com.linksfield.topup.entity.servserapi.queryorder.request.RequestordersQueryNew;
import com.linksfield.topup.entity.servserapi.queryorder.response.ResponseordersQueryNew;
import com.linksfield.topup.mapper.PartnerConfigMapper;
import com.linksfield.topup.mapper.SysOperateMapper;
import com.linksfield.topup.utils.*;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("utilsService")
@Transactional(rollbackFor = Exception.class)

/**
 * 公共工具服务实现类
 *
 * @author: lm
 * @date: 2019-12-05 10:58
 */
@Slf4j
public class CommonUtilsServiceImpl {
    @Resource
    private SysOperateMapper operateMapper;

    @Resource
    private PartnerConfigMapper configMapper;

    @Autowired
    TimeFormatOutputUtil timeUtil;
    /**
     * 3.0接口：请求北京企业网关的地址
     */
    @Value("${jsonIot3.JSON_BASE_URL}")
    private String jsonBaseURL3;
    /**
     * 3.0接口：请求北京企业网关的版本
     */
    @Value("${jsonIot3.VERSION}")
    private String version;

    /****
     * 通用：不验证是管理员还是普通企业
     * 验证 x-access-token的有效性
     * @param token
     * @return
     */
    public String checkToken(String token) {

        if (StringUtils.isBlank(token)) {
            return StringOutputConstant.CODE_TOKEN_EMPTY;
        }
        Claims claims = JwtUtil.parseJWT(token);

        if (null == claims) {
            return StringOutputConstant.CODE_TOKEN_INVALID;
        }
        String account = (String) claims.get(StringOutputConstant.CODE_USERNAME);
        String password = (String) claims.get(StringOutputConstant.CODE_USERPWD);

        Integer c = operateMapper.queryAccount(account);
        if (c <= 0) {
            log.info("账号不存在");
            return StringOutputConstant.CODE_ACCOUNT_ERROR;
        }

        SysOperate user = operateMapper.checkLogin(account, password);
        if (null == user) {
            return StringOutputConstant.CODE_PASSWORD_ERROR;
        }

        //看看输入的账号和实际的账号是不是一致的，主要是中英文方面
        if (!user.getOperAccount().equals(account)) {
            log.info("账号不存在");
            return StringOutputConstant.CODE_ACCOUNT_ERROR;
        }

        //用户被锁定
        if (StringOutputConstant.CODE_BLOCK.equals(user.getOperStatus())) {
            return StringOutputConstant.CODE_ACCOUNT_BLOCK_ERROR;
        }

        if (StringUtils.isBlank(user.getToken()) || !user.getToken().equals(token)) {
            return StringOutputConstant.CODE_SAME_TIME_LOGIN_ERROR;
        }

        return StringOutputConstant.CODE_SUCCESS;
    }

    /****
     *此方法验证：管理员才可通过
     * 验证 x-access-token的有效性,同时验证权限
     * @param token
     * @return
     */
    public String checkAdmin(String token) {

        if (StringUtils.isBlank(token)) {
            return StringOutputConstant.CODE_TOKEN_EMPTY;
        }
        Claims claims = JwtUtil.parseJWT(token);
        if (null == claims) {
            return StringOutputConstant.CODE_TOKEN_INVALID;
        }
        if (StringUtils.isBlank((String) claims.get(StringOutputConstant.CODE_USERNAME)) || StringUtils.isBlank((String) claims.get(StringOutputConstant.CODE_USERPWD))) {
            return StringOutputConstant.CODE_TOKEN_INVALID;
        }
        String account = (String) claims.get(StringOutputConstant.CODE_USERNAME);
        String password = (String) claims.get(StringOutputConstant.CODE_USERPWD);

        Integer c = operateMapper.queryAccount(account);
        if (c <= 0) {
            log.info("账号不存在");
            return StringOutputConstant.CODE_ACCOUNT_ERROR;
        }

        SysOperate user = operateMapper.checkLogin(account, password);

        if (null == user) {
            return StringOutputConstant.CODE_PASSWORD_ERROR;
        }

        //看看输入的账号和实际的账号是不是一致的，主要是中英文方面
        if (!user.getOperAccount().equals(account)) {
            log.info("账号不存在");
            return StringOutputConstant.CODE_ACCOUNT_ERROR;
        }

        //用户被锁定
        if (user.getOperStatus().equals(StringOutputConstant.CODE_BLOCK)) {
            return StringOutputConstant.CODE_ACCOUNT_BLOCK_ERROR;
        }
        //普通用户无权限操作此项
        if (user.getRolesId().equals(StringOutputConstant.CODE_PARTNER)) {
            return StringOutputConstant.CODE_PARTNER_LIMIT_ERROR;
        }
        if (StringUtils.isBlank(user.getToken()) || !user.getToken().equals(token)) {
            return StringOutputConstant.CODE_SAME_TIME_LOGIN_ERROR;
        }
        return StringOutputConstant.CODE_SUCCESS;
    }

    /****
     * 此方法验证：普通企业才可通过
     * 验证 x-access-token的有效性,同时验证权限
     * @param token
     * @return
     */
    public String checkPartner(String token) {

        if (StringUtils.isBlank(token)) {
            return StringOutputConstant.CODE_TOKEN_EMPTY;
        }
        Claims claims = JwtUtil.parseJWT(token);
        if (null == claims) {
            return StringOutputConstant.CODE_TOKEN_INVALID;
        }
        if (StringUtils.isBlank((String) claims.get(StringOutputConstant.CODE_USERNAME)) || StringUtils.isBlank((String) claims.get(StringOutputConstant.CODE_USERPWD))) {
            return StringOutputConstant.CODE_TOKEN_INVALID;
        }
        String account = (String) claims.get(StringOutputConstant.CODE_USERNAME);
        String password = (String) claims.get(StringOutputConstant.CODE_USERPWD);

        Integer c = operateMapper.queryAccount(account);
        if (c <= 0) {
            log.info("账号不存在");
            return StringOutputConstant.CODE_ACCOUNT_ERROR;
        }
        SysOperate user = operateMapper.checkLogin(account, password);

        if (null == user) {
            return StringOutputConstant.CODE_PASSWORD_ERROR;
        }

        //看看输入的账号和实际的账号是不是一致的，主要是中英文方面
        if (!user.getOperAccount().equals(account)) {
            log.info("账号不存在");
            return StringOutputConstant.CODE_ACCOUNT_ERROR;
        }

        //用户被锁定
        if (user.getOperStatus().equals(StringOutputConstant.CODE_BLOCK)) {
            return StringOutputConstant.CODE_ACCOUNT_BLOCK_ERROR;
        }
        //管理员无权限操作此项
        if (user.getRolesId().equals(StringOutputConstant.CODE_ADMIN)) {
            return StringOutputConstant.CODE_ADMIN_LIMIT_ERROR;
        }

        if (StringUtils.isBlank(user.getToken()) || !user.getToken().equals(token)) {
            return StringOutputConstant.CODE_SAME_TIME_LOGIN_ERROR;
        }
        return StringOutputConstant.CODE_SUCCESS;
    }

    /***
     *  Str字符串做去重处理 :覆盖大洲，覆盖国家：都一样
     * @param
     * @return
     */
    public String duplicateRemoval(String Str) {
        //大洲
        if (StringUtils.isNotBlank(Str)) {
            //将数据库取到的数据做去重处理
            String[] str = Str.split(";");
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < str.length; i++) {
                if (!list.contains(str[i])) {
                    list.add(str[i]);
                }
            }
            return Joiner.on(",").join(list);

        } else {
            return "—";
        }

    }

    /**
     * 去更新方案中的updateDate字段时间
     *
     * @param planCode
     * @param partnerCode
     */
    public void updateConfigContentDate(String planCode, String partnerCode) {
        PartnerConfigContent content = new PartnerConfigContent();
        content.setPlanCode(planCode);
        content.setPartnerCode(partnerCode);
        content.setUpdateDate(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
        configMapper.updateConfigContentDate(content);

    }


    /***
     * 新建内容配置公共方法
     * //入库：partner_config_content_t
     * @param partnerCode
     * @param partnerName
     * @param configType
     * @param configStatus
     * @param showContent
     * @param linkURL
     * @param payConfig
     * @param file
     * @return
     */
    public Integer planCreateConfigContent(String planCode,
                                           String partnerCode,
                                           String partnerName,
                                           String configType,
                                           String configStatus,
                                           String showContent,
                                           String linkURL,
                                           String payConfig,
                                           MultipartFile fileListPc,
                                           MultipartFile fileListPh) {

        PartnerConfigContent content = new PartnerConfigContent();
        content.setPlanCode(planCode);
        content.setPartnerCode(partnerCode);
        content.setPartnerName(partnerName);
        content.setConfigType(configType);
        content.setConfigStatus(configStatus);
        content.setShowContent(showContent);
        content.setLinkURL(linkURL);
        content.setPayConfig(payConfig);

        //1,传pc背景图片到服务器上，上传无误会返回一个英文地址

        if (null != fileListPc && !fileListPc.isEmpty()) {

            String uploadResult = UploadUtil.uploadPic(fileListPc, partnerCode, configType, "pc");

            if (!UploadUtil.isChinese(uploadResult)) {
                content.setPcBgimg(uploadResult);
            } else {
                // 上报的参数有误
                return 0;
            }

        } else {
            content.setPcBgimg("");
        }

        //2,传ph背景图片到服务器上，上传无误会返回一个英文地址
        if (null != fileListPh && !fileListPh.isEmpty()) {

            String uploadResult = UploadUtil.uploadPic(fileListPh, partnerCode, configType, "ph");

            if (!UploadUtil.isChinese(uploadResult)) {
                content.setPhBgimg(uploadResult);
            } else {
                // 上报的参数有误
                return 0;
            }

        } else {
            content.setPhBgimg("");
        }

        //方案内容配置入库
        Integer c = configMapper.planCreateConfigContent(content);
        if (c > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    /***
     * 编辑：内容配置
     * 更新：partner_config_content_t
     * @param partnerCode
     * @param configType
     * @param configStatus
     * @param showContent
     * @param linkURL
     * @return
     */
    public Integer editPlanConfigContent(String planCode,
                                         String partnerCode,
                                         String configType,
                                         String configStatus,
                                         String showContent,
                                         String linkURL,
                                         MultipartFile fileListPc,
                                         MultipartFile fileListPh) {

        Integer c;

        if (null != fileListPc && !fileListPc.isEmpty() && null != fileListPh && !fileListPh.isEmpty()) {
            //有图片时的修改
            PartnerConfigContent content = new PartnerConfigContent();
            content.setPlanCode(planCode);
            content.setPartnerCode(partnerCode);
            content.setConfigType(configType);
            content.setConfigStatus(configStatus);
            content.setShowContent(showContent);
            content.setLinkURL(linkURL);

            //1,传pc背景图片到服务器上，上传无误会返回一个英文地址
            String uploadPc = UploadUtil.uploadPic(fileListPc, partnerCode, configType, "pc");

            if (!UploadUtil.isChinese(uploadPc)) {
                content.setPcBgimg(uploadPc);
            } else {
                // 上报的参数有误
                return 0;
            }

            //2,传ph背景图片到服务器上，上传无误会返回一个英文地址
            String uploadResult = UploadUtil.uploadPic(fileListPh, partnerCode, configType, "ph");

            if (!UploadUtil.isChinese(uploadResult)) {
                content.setPhBgimg(uploadResult);
            } else {
                // 上报的参数有误
                return 0;
            }
            //方案内容配置更新
            c = configMapper.editPlanConfigContentWithFile(content);


        } else {
            //没有图片时的修改
            PartnerConfigContent content = new PartnerConfigContent();
            content.setPlanCode(planCode);
            content.setPartnerCode(partnerCode);
            content.setConfigType(configType);
            content.setConfigStatus(configStatus);
            content.setShowContent(showContent);
            content.setLinkURL(linkURL);
            //方案内容配置更新
            c = configMapper.editPlanConfigContentNotFile(content);
        }

        if (c > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    /***
     * 新建语言配置公共方法
     * //入库：partner_config_lang_t
     * @param languageCode
     * @param languageName
     * @param languagePriority
     * @param welcomeLang
     * @param partnerCode
     * @param configType
     * @param popupContent
     * @return
     */
    public Integer planCreateConfigLang(String planCode,
                                        String languageCode,
                                        String languageName,
                                        String languagePriority,
                                        String welcomeLang,
                                        String partnerCode,
                                        String configType,
                                        String popupContent) {

        PartnerConfigLang lang = new PartnerConfigLang();
        lang.setPlanCode(planCode);
        lang.setLanguageCode(languageCode);
        lang.setLanguageName(languageName);
        lang.setLanguagePriority(languagePriority);
        lang.setWelcomeLang(welcomeLang);
        lang.setPartnerCode(partnerCode);
        lang.setConfigType(configType);
        lang.setPopupContent(popupContent);
        //语言配置内容入库
        Integer count = configMapper.planCreateConfigLang(lang);

        if (count > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    /***
     * 编辑：语言文本配置
     * 更新：partner_config_lang_t
     * @param languageCode
     * @param languageName
     * @param languagePriority
     * @param welcomeLang
     * @param partnerCode
     * @param configType
     * @param popupContent
     * @return
     */
    public Integer editPlanConfigLang(String planCode,
                                      String languageCode,
                                      String languageName,
                                      String languagePriority,
                                      String welcomeLang,
                                      String partnerCode,
                                      String configType,
                                      String popupContent) {

        PartnerConfigLang lang = new PartnerConfigLang();
        lang.setPlanCode(planCode);
        lang.setLanguageCode(languageCode);
        lang.setLanguageName(languageName);
        lang.setLanguagePriority(languagePriority);
        lang.setWelcomeLang(welcomeLang);
        lang.setPartnerCode(partnerCode);
        lang.setConfigType(configType);
        lang.setPopupContent(popupContent);
        //语言配置内容入库
        Integer count = configMapper.editPlanConfigLang(lang);

        if (count > 0) {
            return 1;
        } else {
            return 0;
        }

    }

    /***
     * 背景图片编辑
     * @param partnerCode
     * @param configType
     * @param configStatus
     * @param file
     * @return
     */
    public Integer secondContentEdit(String planCode,
                                     String partnerCode,
                                     String configType,
                                     String configStatus,
                                     MultipartFile fileListPc,
                                     MultipartFile fileListPh) {

        PartnerConfigContent content = new PartnerConfigContent();
        content.setPlanCode(planCode);
        content.setPartnerCode(partnerCode);
        content.setConfigType(configType);
        content.setConfigStatus(configStatus);

        //pc的图片上传到服务器
        if (null != fileListPc && !fileListPc.isEmpty()) {

            String uploadResult = UploadUtil.uploadPic(fileListPc, partnerCode, configType, "pc");

            if (!UploadUtil.isChinese(uploadResult)) {
                content.setPcBgimg(uploadResult);
            } else {
                // 上报的参数有误
                return 0;
            }
        } else {
            return 0;
        }

        //ph的图片上传到服务器
        if (null != fileListPh && !fileListPh.isEmpty()) {

            String uploadResult = UploadUtil.uploadPic(fileListPh, partnerCode, configType, "ph");

            if (!UploadUtil.isChinese(uploadResult)) {
                content.setPhBgimg(uploadResult);
            } else {
                // 上报的参数有误
                return 0;
            }
        } else {
            return 0;
        }

        //方案内容配置入库
        Integer c = configMapper.secondContentEdit(content);
        if (c > 0) {
            return 1;
        } else {
            return 0;
        }

    }

    /***
     * 新建支付配置公共方法
     * //入库：partner_config_pay_t
     * @param partnerCode
     * @param payType
     * @param mode
     * @param clientId
     * @param clientSecret
     * @return
     */
    public Integer planCreateConfigPay(String planCode,
                                       String partnerCode,
                                       String payType,
                                       String mode,
                                       String clientId,
                                       String clientSecret) {
        PartnerConfigPay pay = new PartnerConfigPay();
        pay.setPlanCode(planCode);
        pay.setPartnerCode(partnerCode);
        pay.setPayType(payType);
        pay.setMode(mode);
        pay.setClientId(clientId);
        pay.setClientSecret(clientSecret);
        //支付配置内容入库
        Integer count = configMapper.planCreateConfigPay(pay);
        if (count > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    /***
     * 更新支付配置表的公共方法
     * 更新数据表：partner_config_pay_t
     * @param partnerCode
     * @param payType
     * @param mode
     * @param clientId
     * @param clientSecret
     * @return
     */
    public Integer editPlanConfigPay(String planCode,
                                     String partnerCode,
                                     String payType,
                                     String mode,
                                     String clientId,
                                     String clientSecret) {

        PartnerConfigPay pay = new PartnerConfigPay();
        pay.setPlanCode(planCode);
        pay.setPartnerCode(partnerCode);
        pay.setPayType(payType);
        pay.setMode(mode);
        pay.setClientId(clientId);
        pay.setClientSecret(clientSecret);
        //支付配置内容更新
        Integer count = configMapper.editPlanConfigPay(pay);
        if (count > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    /***
     * 编辑：方案四支付内容配置(将payConfig的值更新到内容数据表)
     * @param partnerCode
     * @param configType
     * @param configStatus
     * @param payConfig
     * @return
     */
    public Integer editPayConfigContent(String planCode,
                                        String partnerCode,
                                        String configType,
                                        String configStatus,
                                        String payConfig,
                                        MultipartFile fileListPc,
                                        MultipartFile fileListPh) {
        Integer c;
        if (null != fileListPc && !fileListPc.isEmpty() && null != fileListPh && !fileListPh.isEmpty()) {
            //有图片文件一起的方案四内容修改
            PartnerConfigContent content = new PartnerConfigContent();
            content.setPlanCode(planCode);
            content.setPartnerCode(partnerCode);
            content.setConfigType(configType);
            content.setConfigStatus(configStatus);
            content.setPayConfig(payConfig);
            //1,传pc背景图片到服务器上，上传无误会返回一个英文地址

            String uploadPc = UploadUtil.uploadPic(fileListPc, partnerCode, configType, "pc");
            if (!UploadUtil.isChinese(uploadPc)) {
                content.setPcBgimg(uploadPc);
            } else {
                return 0;
            }

            //2,传ph背景图片到服务器上，上传无误会返回一个英文地址
            String uploadPh = UploadUtil.uploadPic(fileListPh, partnerCode, configType, "ph");
            if (!UploadUtil.isChinese(uploadPh)) {
                content.setPhBgimg(uploadPh);
            } else {
                return 0;
            }

            //方案内容配置更新
            c = configMapper.editPayConfigContentWithFile(content);

        } else {
            PartnerConfigContent content = new PartnerConfigContent();
            content.setPlanCode(planCode);
            content.setPartnerCode(partnerCode);
            content.setConfigType(configType);
            content.setConfigStatus(configStatus);
            content.setPayConfig(payConfig);
            //方案内容配置更新
            c = configMapper.editPayConfigContentNotFile(content);
        }

        if (c > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 将获取到的计算列表List转成可以直接返回的Object
     *
     * @param voList
     * @return
     */
    public CalculateResultParamVo convertListToObject(List<CalculateResultParamVo> voList) {

        CalculateResultParamVo vo = new CalculateResultParamVo();
        if (null != voList && !voList.isEmpty()) {
            for (CalculateResultParamVo ca : voList) {
                if (null != ca.getOrderCount()) {
                    vo.setOrderCount(ca.getOrderCount());
                } else {
                    vo.setOrderCount(0);
                }

                if (null != ca.getOrderMoney()) {
                    vo.setOrderMoney(ca.getOrderMoney());
                } else {
                    vo.setOrderMoney((double) 0);
                }
            }
        } else {
            vo.setOrderCount(0);
            vo.setOrderMoney((double) 0);
        }

        return vo;
    }

    /**
     * 处理既有订单数量，又有订单总金额的list集合
     * <p>
     * 将获取到的计算列表List转成可以直接返回的List<Map<String, Object>>
     * <p>
     * 如果日期列表中某一个日期未查询到对应的订单条数，订单总金额：
     * <p>
     * 需要补全日期对应补齐订单条数为0，订单总金额为0.00
     *
     * @param dateList
     * @param voList
     * @return
     */
    public List<Map<String, Object>> dealOrderCountAndMoney(List<String> dateList, ArrayList<CalculateResultParamVo> voList) {

        List<Map<String, Object>> mapList = new ArrayList<>();
        //key :日期  value：数值
        for (CalculateResultParamVo vo : voList) {
            Map<String, Object> map = new HashMap<>();
            map.put("date", vo.getDates());
            map.put("orderCount", vo.getOrderCount());
            map.put("orderMoney", vo.getOrderMoney());
            mapList.add(map);
        }
        boolean flag;
        for (int i = 0; i < dateList.size(); i++) {
            flag = false;
            for (Map<String, Object> hs : mapList) {
                if (dateList.get(i).equals(hs.get("date"))) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                final String date1 = dateList.get(i);
                mapList.add(i, new HashMap<String, Object>() {{
                    put("date", date1);
                    put("orderCount", 0);
                    put("orderMoney", 0);

                }});
            }
        }
        return mapList;
    }

    /**
     * 处理查询结果只有日期和对应订单数量的情况
     *
     * @param dateList
     * @param voList
     * @return
     */
    public List<Map<String, Object>> dealOrderCount(List<String> dateList, ArrayList<CalculateResultParamVo> voList) {

        List<Map<String, Object>> mapList = new ArrayList<>();
        //key :日期  value：数值
        for (CalculateResultParamVo vo : voList) {
            Map<String, Object> map = new HashMap<>();
            map.put("date", vo.getDates());
            map.put("orderCount", vo.getOrderCount());
            mapList.add(map);
        }
        boolean flag;
        for (int i = 0; i < dateList.size(); i++) {
            flag = false;
            for (Map<String, Object> hs : mapList) {
                if (dateList.get(i).equals(hs.get("date"))) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                final String date1 = dateList.get(i);
                mapList.add(i, new HashMap<String, Object>() {{
                    put("date", date1);
                    put("orderCount", 0);

                }});
            }
        }
        return mapList;
    }

    /**
     * 处理查询结果只有日期和对应订单总金额的情况
     *
     * @param dateList
     * @param voList
     * @return
     */
    public List<Map<String, Object>> dealOrderMoney(List<String> dateList, ArrayList<CalculateResultParamVo> voList) {

        List<Map<String, Object>> mapList = new ArrayList<>();
        //key :日期  value：数值
        for (CalculateResultParamVo vo : voList) {
            Map<String, Object> map = new HashMap<>();
            map.put("date", vo.getDates());
            map.put("orderMoney", vo.getOrderMoney());
            mapList.add(map);
        }
        boolean flag;
        for (int i = 0; i < dateList.size(); i++) {
            flag = false;
            for (Map<String, Object> hs : mapList) {
                if (dateList.get(i).equals(hs.get("date"))) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                final String date1 = dateList.get(i);
                mapList.add(i, new HashMap<String, Object>() {{
                    put("date", date1);
                    put("orderMoney", 0);

                }});
            }

        }
        return mapList;
    }

    /**
     * 查询需要查询或者显示的的日期列表
     *
     * @param mark
     * @param date
     * @return
     */
    public List<String> findDateList(String mark, String date) {

        List<String> dateList;
        //这边开始按照不同的mark值去组织first和last

        if (StringOutputConstant.CODE_ONE.equals(mark)) {

            //3，根据请求的年份去判断出我们应该在折线图上反应哪些月份对应的数据
            String first = date + "-01";
            //4，判断一下单月的情况，只允许展示到本月
            String last = findLastDate(date, mark);
            //5,按照输入日期去获得应该被查询的月份list列表
            dateList = timeUtil.getMonthBetween(first, last);
        } else {
            //3，根据请求的月份日期去判断出我们应该在折线图上反应哪些日期对应的数据
            String dataDate = date + "-01 11:11:11";
            String first = timeUtil.getFirstDay(dataDate);
            //4，判断一下单月的情况，只允许展示到今天，lastDay就为今天
            String last = findLastDate(date, mark);
            //5,按照输入日期去获得应该被查询的日期list列表
            dateList = timeUtil.getDateBetween(first, last);
        }
        return dateList;
    }

    /**
     * 输入一个yyyy或者一个yyyy-MM日期，判断需要显示的最后一个day或者month
     *
     * @param date
     * @param mark
     * @return
     */
    public String findLastDate(String date, String mark) {
        String last;

        if (StringOutputConstant.CODE_ONE.equals(mark)) {
            if (timeUtil.currentYear().equals(date)) {
                last = timeUtil.currentMonth();
            } else {
                last = date + "-12";
            }
        } else {
            String dataDate = date + "-01 11:11:11";
            //4，判断一下单月的情况，只允许展示到今天，lastDay就为今天
            if (timeUtil.currentMonth().equals(date)) {
                last = timeUtil.currentDay();
            } else {
                last = timeUtil.getLastDay(dataDate);
            }

        }
        return last;
    }

    /**
     * 原始套餐可订购范围
     *
     * @param packageType
     * @param minOrderPeriod
     * @param maxOrderPeriod
     * @return
     */
    public String setAvailableRange(String packageType, String minOrderPeriod, String maxOrderPeriod) {
        String result;
        if (StringOutputConstant.CODE_ZERO.equals(packageType) || StringOutputConstant.CODE_ONE.equals(packageType)) {
            if (StringOutputConstant.CODE_MINUS_ONE.equals(maxOrderPeriod)) {
                result = "最小值:" + minOrderPeriod + "天;最大值:无上限";
            } else {
                result = "最小值:" + minOrderPeriod + "天;最大值:" + maxOrderPeriod + "天";
            }
        } else if (StringOutputConstant.CODE_TWO.equals(packageType)) {
            if (StringOutputConstant.CODE_MINUS_ONE.equals(maxOrderPeriod)) {
                result = "最小值:" + minOrderPeriod + "个月;最大值:无上限";
            } else {
                result = "最小值:" + minOrderPeriod + "个月;最大值:" + maxOrderPeriod + "个月";
            }
        } else if (StringOutputConstant.CODE_THREE.equals(packageType)) {
            if (StringOutputConstant.CODE_MINUS_ONE.equals(maxOrderPeriod)) {
                result = "最小值:" + minOrderPeriod + "个季度;最大值:无上限";
            } else {
                result = "最小值:" + minOrderPeriod + "个季度;最大值:" + maxOrderPeriod + "个季度";
            }
        } else if (StringOutputConstant.CODE_FOUR.equals(packageType)) {
            if (StringOutputConstant.CODE_MINUS_ONE.equals(maxOrderPeriod)) {
                result = "最小值:" + minOrderPeriod + "个半年;最大值:无上限";
            } else {
                result = "最小值:" + minOrderPeriod + "个半年;最大值:" + maxOrderPeriod + "个半年";
            }
        } else if (StringOutputConstant.CODE_FIVE.equals(packageType)) {
            if (StringOutputConstant.CODE_MINUS_ONE.equals(maxOrderPeriod)) {
                result = "最小值:" + minOrderPeriod + "年;最大值:无上限";
            } else {
                result = "最小值:" + minOrderPeriod + "年;最大值:" + maxOrderPeriod + "年";
            }
        } else if (StringOutputConstant.CODE_SIX.equals(packageType)) {
            if (StringOutputConstant.CODE_MINUS_ONE.equals(maxOrderPeriod)) {
                result = "最小值:" + minOrderPeriod + "个4个月;最大值:无上限";
            } else {
                result = "最小值:" + minOrderPeriod + "个4个月;最大值:" + maxOrderPeriod + "个4个月";
            }
        } else if (StringOutputConstant.CODE_SEVEN.equals(packageType)) {
            if (StringOutputConstant.CODE_MINUS_ONE.equals(maxOrderPeriod)) {
                result = "最小值:" + minOrderPeriod + "个18个月;最大值:无上限";
            } else {
                result = "最小值:" + minOrderPeriod + "个18个月;最大值:" + maxOrderPeriod + "个18个月";
            }
        } else if (StringOutputConstant.CODE_EIGHT.equals(packageType)) {
            if (StringOutputConstant.CODE_MINUS_ONE.equals(maxOrderPeriod)) {
                result = "最小值:" + minOrderPeriod + "个两年;最大值:无上限";
            } else {
                result = "最小值:" + minOrderPeriod + "个两年;最大值:" + maxOrderPeriod + "个两年";
            }
        } else {
            if (StringOutputConstant.CODE_MINUS_ONE.equals(maxOrderPeriod)) {
                result = "最小值:" + minOrderPeriod + "个未定义;最大值:无上限";
            } else {
                result = "最小值:" + minOrderPeriod + "个未定义;最大值:" + maxOrderPeriod + "个未定义";
            }
        }
        return result;
    }

    /**
     * 原始套餐类型的单位
     *
     * @param packageType
     * @return
     */
    public String setPackageUnit(String packageType) {
        String result;
        if (StringOutputConstant.CODE_ZERO.equals(packageType) ||
                StringOutputConstant.CODE_ONE.equals(packageType)) {
            result = "天";
        } else if (StringOutputConstant.CODE_TWO.equals(packageType)) {
            result = "月";
        } else if (StringOutputConstant.CODE_THREE.equals(packageType)) {
            result = "季度";
        } else if (StringOutputConstant.CODE_FOUR.equals(packageType)) {
            result = "半年";
        } else if (StringOutputConstant.CODE_FIVE.equals(packageType)) {
            result = "年";
        } else if (StringOutputConstant.CODE_SIX.equals(packageType)) {
            result = "4个月";
        } else if (StringOutputConstant.CODE_SEVEN.equals(packageType)) {
            result = "18个月";
        } else if (StringOutputConstant.CODE_EIGHT.equals(packageType)) {
            result = "两年";
        } else {
            result = "未定义";
        }
        return result;
    }

    /**
     * 根据套餐类型返回周期单位
     *
     * @param packageType
     * @return
     */
    public String getUnit(String packageType) {

        if (StringOutputConstant.CODE_ZERO.equals(packageType) ||
                StringOutputConstant.CODE_ONE.equals(packageType)) {
            return "天";
        } else if (StringOutputConstant.CODE_TWO.equals(packageType)) {
            return "个月";
        } else if (StringOutputConstant.CODE_THREE.equals(packageType)) {
            return "个季度";
        } else if (StringOutputConstant.CODE_FOUR.equals(packageType)) {
            return "个半年";
        } else if (StringOutputConstant.CODE_FIVE.equals(packageType)) {
            return "年";
        } else if (StringOutputConstant.CODE_SIX.equals(packageType)) {
            return "个4个月";
        } else if (StringOutputConstant.CODE_SEVEN.equals(packageType)) {
            return "个18个月";
        } else if (StringOutputConstant.CODE_EIGHT.equals(packageType)) {
            return "个两年";
        } else {
            return "个未定义";
        }
    }

    /**
     * 原始套餐类型展示
     *
     * @param packageType
     * @return
     */
    public String setPackageTypeShow(String packageType) {
        String result;
        if (StringOutputConstant.CODE_ZERO.equals(packageType)) {
            result = "日程套餐";
        } else if (StringOutputConstant.CODE_ONE.equals(packageType)) {
            result = "日流量套餐";
        } else if (StringOutputConstant.CODE_TWO.equals(packageType)) {
            result = "月流量套餐";
        } else if (StringOutputConstant.CODE_THREE.equals(packageType)) {
            result = "季度流量套餐";
        } else if (StringOutputConstant.CODE_FOUR.equals(packageType)) {
            result = "半年流量套餐";
        } else if (StringOutputConstant.CODE_FIVE.equals(packageType)) {
            result = "年流量套餐";
        } else if (StringOutputConstant.CODE_SIX.equals(packageType)) {
            result = "4个月流量套餐";
        } else if (StringOutputConstant.CODE_SEVEN.equals(packageType)) {
            result = "18个月流量套餐";
        } else if (StringOutputConstant.CODE_EIGHT.equals(packageType)) {
            result = "两年流量套餐";
        } else {
            result = "未定义流量套餐";
        }
        return result;
    }

    /**
     * 设置订购周期的显示字段
     *
     * @param packageType
     * @param orderPeriod
     * @return
     */
    public String setOrderPeriod(String packageType, String orderPeriod) {
        String result;
        if (StringOutputConstant.CODE_ZERO.equals(packageType)) {
            result = orderPeriod + "天";
        } else if (StringOutputConstant.CODE_ONE.equals(packageType)) {
            result = orderPeriod + "天";
        } else if (StringOutputConstant.CODE_TWO.equals(packageType)) {
            result = orderPeriod + "个月";
        } else if (StringOutputConstant.CODE_THREE.equals(packageType)) {
            result = orderPeriod + "个季度";
        } else if (StringOutputConstant.CODE_FOUR.equals(packageType)) {
            result = orderPeriod + "个半年";
        } else if (StringOutputConstant.CODE_FIVE.equals(packageType)) {
            result = orderPeriod + "年";
        } else if (StringOutputConstant.CODE_SIX.equals(packageType)) {
            result = orderPeriod + "个4个月";
        } else if (StringOutputConstant.CODE_SEVEN.equals(packageType)) {
            result = orderPeriod + "个18个月";
        } else if (StringOutputConstant.CODE_EIGHT.equals(packageType)) {
            result = orderPeriod + "个两年";
        } else {
            result = orderPeriod + "个未定义";
        }
        return result;
    }

    /**
     * 设置订单状态参数
     *
     * @param packageStatus
     * @return
     */
    public String setPackageStatus(String packageStatus) {
        String result = "-";
        if (StringUtils.isNoneBlank(packageStatus)) {
            if (packageStatus.equals(StringOutputConstant.CODE_ONE)) {
                result = "未启用";
            } else if (packageStatus.equals(StringOutputConstant.CODE_TWO)) {
                result = "已启用";
            }
        }
        return result;
    }

    /**
     * 设置支付状态参数
     *
     * @param payStatus
     * @return
     */
    public String setPayStatus(String payStatus) {
        String result = "-";
        if (payStatus.equals(StringOutputConstant.CODE_ONE)) {
            result = "已支付";
        } else if (payStatus.equals(StringOutputConstant.CODE_TWO)) {
            result = "已退款";
        }
        return result;
    }

    /**
     * 设置支付方式参数
     *
     * @param payType
     * @return
     */
    public String setPayType(String payType) {
        String result = "其他支付";
        if (StringOutputConstant.CODE_ONE.equals(payType)) {
            result = "微信支付";
        } else if (StringOutputConstant.CODE_TWO.equals(payType)) {
            result = "PayPal支付";
        } else if (StringOutputConstant.CODE_ZERO.equals(payType)) {
            result = "B端自行收款";
        } else if (StringOutputConstant.CODE_THREE.equals(payType)) {
            result = "Stripe支付";
        }
        return result;
    }

    /**
     * 设置收款参数
     *
     * @param payAccount
     * @return
     */
    public String setPayAccount(String payAccount) {
        String result;
        if (StringOutputConstant.CODE_ONE.equals(payAccount)) {
            result = "领科收款";
        } else {
            result = "B端收款";
        }
        return result;
    }

    /**
     * 设置支付金额参数
     *
     * @param payCurrency
     * @param payAmount
     * @return
     */
    public String setPayAmount(String payCurrency, String payAmount) {
        String result;
        if (StringUtils.isNotBlank(payCurrency) && StringUtils.isNotBlank(payAmount) && StringOutputConstant.CODE_USD.equalsIgnoreCase(payCurrency)) {
            result = "$" + " " + payAmount;
        } else if (StringUtils.isNotBlank(payCurrency) && StringUtils.isNotBlank(payAmount) && StringOutputConstant.CODE_EUR.equalsIgnoreCase(payCurrency)) {
            result = "€" + " " + payAmount;
        } else {
            result = "￥" + " " + payAmount;
        }
        return result;
    }

    /**
     * 设置payMode 交易类型：交易类型，也是付款模式：0-单次购买；1-周期订阅（自动订阅）
     *
     * @param payMode
     * @return
     */
    public String setPayMode(String payMode) {
        String result = "-";
        if (StringOutputConstant.CODE_ZERO.equals(payMode)) {
            result = "单次购买";
        } else if (StringOutputConstant.CODE_ONE.equals(payMode)) {
            result = "自动订阅";
        }
        return result;
    }

    /**
     * 设置订阅周期 ：intervalCount+intervals（Day,Month,Year）
     *
     * @param intervals
     * @param intervalCount
     * @return
     */
    public String setIntervals(String intervals, String intervalCount) {
        String result = "-";
        if (StringUtils.isNotBlank(intervals) && StringUtils.isNotBlank(intervalCount) && StringOutputConstant.CODE_DAY.equalsIgnoreCase(intervals)) {
            result = intervalCount + "天";
        } else if (StringUtils.isNotBlank(intervals) && StringUtils.isNotBlank(intervalCount) && StringOutputConstant.CODE_MONTH.equalsIgnoreCase(intervals)) {
            result = intervalCount + "个月";
        } else if (StringUtils.isNotBlank(intervals) && StringUtils.isNotBlank(intervalCount) && StringOutputConstant.CODE_YEAR.equalsIgnoreCase(intervals)) {
            result = intervalCount + "年";
        }
        return result;
    }

    /**
     * 设置订阅状态 ：active-生效 ；canceled-失效
     *
     * @param status
     * @return
     */
    public String setStatus(String status) {
        String result = "-";
        if (StringOutputConstant.CODE_ACTIVE.equalsIgnoreCase(status)) {
            result = "生效";
        } else if (StringOutputConstant.CODE_CANCELED.equalsIgnoreCase(status)) {
            result = "失效";
        }
        return result;
    }

    /**
     * 组装PageAndSort数据的方法
     *
     * @param rp
     * @param currentPage
     * @return
     */
    public PageAndSort buildUpPageAndSort(Integer rp, Integer currentPage, long rowCount) {
        /*如果前端未指定查询页码和显示多少行*/
        Integer pageRows;
        if (null != rp) {
            pageRows = rp;
        } else {
            pageRows = 10;
        }
        /*如果前端未指定查询页码*/
        Integer pageNumber;
        if (null != currentPage) {
            pageNumber = currentPage;
        } else {
            pageNumber = 1;
        }
        /*计算出来的分页的数据:rowCount总条数*/
        PageAndSort pageHelper = new PageAndSort();
        pageHelper.setPage(pageNumber);
        pageHelper.setRp(pageRows);
        pageHelper.setRowCount(rowCount);

        return pageHelper;
    }

    /**
     * 直接请求企业网关3.0接口
     * <p>
     * 请求北京网关 3.16 查询套餐订单信息
     *
     * @param deviceCode
     * @param orderId
     * @param orderStatus
     * @param orderType
     * @param partnerCode
     * @param secret
     * @return
     */
    public ResponseQueryDeviceOrder queryDeviceOrder(String deviceCode, String orderId, String orderStatus, String orderType, String partnerCode, String secret) {

        RequestQueryDeviceOrder request = new RequestQueryDeviceOrder();
        request.setVersion(version);
        request.setTimestamp(TimeUtil.getTimeInMillis().toString());
        request.setAccess_code(partnerCode);
        request.setDevice_id(deviceCode);

        if (StringUtils.isNotBlank(orderId)) {
            request.setOrder_id(orderId);
        }
        if (StringUtils.isNotBlank(orderType)) {
            request.setOrder_type(orderType);
        }
        if (StringUtils.isNotBlank(orderStatus)) {
            request.setOrder_status(orderStatus);
        }
        request.setPage_no(1);
        request.setPage_size(500);
        try {
            request.setSign(HMACSHA1.jsonSign(request, secret));
        } catch (Exception e) {
            log.info("计算签名出现异常：" + e);
        }
        String queryOrder = JSON.toJSONString(request);
        String response;

        if (StringOutputConstant.CODE_TWO.equals(orderStatus)) {
            log.info("请求查询【正在使用】订单:" + queryOrder);
            //3.0重构的接口
            String url = jsonBaseURL3 + JsonConstant.JSON_QUERY_H5_ORDER;

            // 发送post请求，并接收返回结果
            response = HttpUtil.httpPost(url, queryOrder);
            log.info("url=" + url);
            //replaceAll("\\s*|\t|\r|\n", "")):java去除字符串中的空格、回车、换行符、制表符
            log.info("响应查询【正在使用】订单：" + response.replaceAll("\\s*|\t|\r|\n", ""));
        } else if (StringOutputConstant.CODE_ONE.equals(orderStatus)) {
            log.info("请求查询【未启用】订单:" + queryOrder);
            //3.0重构的接口
            String url = jsonBaseURL3 + JsonConstant.JSON_QUERY_H5_ORDER;

            // 发送post请求，并接收返回结果
            response = HttpUtil.httpPost(url, queryOrder);
            log.info("url=" + url);
            //replaceAll("\\s*|\t|\r|\n", "")):java去除字符串中的空格、回车、换行符、制表符
            log.info("响应查询【未启用】订单：" + response.replaceAll("\\s*|\t|\r|\n", ""));
        } else {
            log.info("请求查询【所有】订单:" + queryOrder);
            //3.0重构的接口
            String url = jsonBaseURL3 + JsonConstant.JSON_QUERY_H5_ORDER;

            // 发送post请求，并接收返回结果
            response = HttpUtil.httpPost(url, queryOrder);
            log.info("url=" + url);
            //replaceAll("\\s*|\t|\r|\n", "")):java去除字符串中的空格、回车、换行符、制表符
            log.info("响应查询【所有】订单：" + response.replaceAll("\\s*|\t|\r|\n", ""));
        }
        //这边验证返回的是"",那么为了程序不报错给返回一个null
        if (StringUtils.isBlank(response)) {
            return null;
        }

        //这边只用验证返回的只要不是""证明请求响应是正常的
        return JSON.parseObject(response, ResponseQueryDeviceOrder.class);
    }
}